// 样式
import styles from "./index.module.scss";

// react
type Props = {}
import React, { useEffect, RefObject, useState } from "react";
// 导入仓库
import { myUserToken, changeUser, changeUserToken} from "@/store/userSlice";
// 导入带有类型的属性，方法 1.
import { useAppDispatch, useAppSelector } from "../../hooks";

// 路由
import { useNavigate, useLocation, redirect } from "react-router-dom";
// antd-ui组件
import { Form, Input, Button, Toast} from "antd-mobile";

// 微信接口
import wxfetch from "../../utils/wxfetch";
// 后端接口
import { ApiSendCaptcha, ApiRegister, ApiCheckLogin, ApiMemberUpdate } from "@/utils/api";


// 导入工具
// 加密解密
import crypt from "@/utils/crypto";

export default function register({}: Props) {
  // 表单更新
  const [form] = Form.useForm();

  // 导入仓库 2.使用属性
  const UserToken = useAppSelector(myUserToken);
  // 导入仓库 2.使用方法
  const dispatch = useAppDispatch();

  // 路由跳转
  const navigate = useNavigate();


  // 去到注册页;
  const pushRegister = () => {
    // window.location.href = "http://127.0.0.1:8080";
    navigate("/register");
  };

  // 用户手机号等
  const [formData, setFormData] = useState({
    name: "",
    sex: 0,
    birthday: null,
    mobile: "",
    captcha: "",
    plate_number: "",
  });

  // 检查并登录的member_id
  const [member_id, setMember_id] = useState(-1);
  // 验证码
  const [sendCode, setSendCode] = useState(false);
  const [num, setNum] = useState(5);
  const [timer, setTimer] = useState();
  // 修改user对象属性值
  const handleFieldChange = <K extends keyof RootObject>(
    fieldName: K,
    value: RootObject[K]
  ) => {
    // console.log(fieldName, value);
    setFormData((prevData) => ({
      ...prevData,
      [fieldName]: value,
    }));
  };

  //  user对象里的属性名 属性值
  const handleNameInputChange = (
    type: keyof RootObject,
    value: RootObject[keyof RootObject]
  ) => {
    // console.log("type", type);
    handleFieldChange(type, value);
    // console.log("formData", formData);
  };

  // 确定注册手机
  const determine = async () => {
    // if (!formData.captcha || !formData.mobile) {
    //   // navigate("/home");
    //   navigate("/home", { replace: true });
    //   return;
    // }
    // const res = await ApiRegister(params);
    // if (res.code == 0) {
    //   //  手机号 存到仓库
    //   dispatch(changeUser(formData));
    //   // 修改登录状态 为true
    //   // dispatch(changeIsLogin());
    //   console.log(res.data, "注册");
    //   // 换成注册状态
    //   // 检查登录状态
    //   await checkLogin(myToken);

    //   // 跳转信息页
    //   // navigate("/index");
    //   navigate("/reinfo");
    // }
  };

  // 请求登录状态
  const checkLogin = async (AccessToken: AccessToken) => {
    console.log(AccessToken.openid, "openid");
    const res = await ApiCheckLogin(AccessToken.openid);
    if (res.code == 0) {
      // 当前页面使用
      setMember_id(res.data.member_id);
      // getMemberInfo(res.data.member_id);
      // 请求用户信息
      return res.data.member_id;
    } else {
      console.log("未登录");
      return;
    }
  };
  // 更新姓名性别
  const deterName = async (wxInfo: wxInfo, member_id: number) => {
    // console.log(wxInfo.openid, "openid");
    // 校验是否有openid和session_member_id
    if (!wxInfo.openid || !member_id) {
      console.log("没有获取openid或没有校验登录");
      return;
    }
    // console.log(wxInfo.openid, "openid");
    // 请求参数
    let myFormData = {
      ...formData,
      sex: wxInfo.sex == 0 ? 1 : 2,
      name: wxInfo.nickname,
      openid: wxInfo.openid,
      session_member_id: member_id,
    };
    console.log(myFormData, "myFormData");
    // 请求修改信息
    const res = await ApiMemberUpdate(myFormData);
    // 请求成功
    if (res.code == 0) {
      //  存到仓库
      dispatch(changeUser(myFormData));
      // 修改登录状态
      // dispatch(changeIsLogin());
      // console.log(res.data, "修改成功");
    }
  };
  // 获取验证码
  const handleSendCodeClick = async () => {
    if (sendCode) {
      // 禁止重新发送
      return;
    }
    // 在这里处理发送验证码的逻辑
    // 获取手机号的值
    const res = await ApiSendCaptcha(formData.mobile);
    // 后续布置阿里云
    setSendCode(true);
    // 倒计时
    const timer = setInterval(() => {
      setNum((prevNum) => {
        if (prevNum === 1) {
          clearInterval(timer);
          setSendCode(false);
          return num; // Reset the countdown
        }
        return prevNum - 1;
      });
    }, 1000);
    if (res.code == 0) {
      handleNameInputChange("captcha", res.data.code);
      Toast.show({ content: "已发送", icon: "success" });
    }
    // console.log("mobile:", formData.mobile);
  };

  // 校验手机号
  const phoneValidator = (_, value, callback) => {
    if (value) {
      let reg =
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      // if (reg.test(value)) {
      //     handleNameInputChange("mobile", value);
      //     return callback();
      // }
      if (reg.test(value)) {
        handleNameInputChange("mobile", value);
        return Promise.resolve();
      }
      return Promise.reject(new Error("手机号无效"));
      // return Promise.reject(new Error("请输入11为数字手机号"));
    } else {
      return Promise.reject(new Error("手机号不得为空"));
    }
  };

  // 失去焦点
  const handleMobileBlur = async (e) => {
    const value = e.target.value;
    try {
      await form.validateFields(["mobile"]);
    } catch (error) {
      // 在这里可以处理验证失败的逻辑，例如显示错误信息
      console.error("Validation failed:", error);
    }
  };

  useEffect(() => {
    // 获取用户信息
    // getCode();
    // 检测是否注册过
  }, []);

  // 更新界面
  // sendCode
  // 挂载页面
  useEffect(() => {
    form.setFieldsValue(formData);
  }, [formData, form]);

  return (
    <div className={styles.form}>
      <Form
        initialValues={{ ...formData }}
        layout="horizontal"
        form={form}
        footer={
          <Button
            block
            type="submit"
            color="primary"
            size="large"
            shape="rounded"
            onClick={determine}
          >
            保存并返回
          </Button>
        }
      >
        <Form.Header>修改手机号</Form.Header>
        <Form.Item
          name="mobile"
          label="手机号"
          // rules={[{ required: true }]}
          rules={[{ validator: phoneValidator }]}
        >
          <Input
            placeholder="请输入新手机号"
            onBlur={handleMobileBlur}
            onChange={(value) => handleNameInputChange("mobile", value)}
          />
        </Form.Item>
        <Form.Item
          name="captcha"
          label="验证码"
          extra={
            <>
              <a
                onClick={handleSendCodeClick}
                style={{ display: sendCode ? "none" : "inline-block" }}
              >
                获取验证码
              </a>
              <span style={{ display: sendCode ? "inline-block" : "none" }}>
                {num}s后可重发
              </span>
            </>
          }
          // rules={[{ required: true }]}
        >
          <Input
            placeholder="请输入验证码"
            onChange={(value) => handleNameInputChange("captcha", value)}
          />
        </Form.Item>
      </Form>
    </div>
  );
}